<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">

	<meta name="baidu-site-verification" content="IwHYiEzBBM" />



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />










  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="android," />





  <link rel="alternate" href="/atom.xml" title="长孙雨聪--七星上将" type="application/atom+xml" />






<meta name="description" content="前言在这篇文章中，将会基于android 26源码上分析Activity从启动到显示到屏幕和Decorview添加到Window中的过程。另外在本文中，省略了很多内容，目的只是从源码中找到一条启动的线索。迟点再补充上流程图。 从startActivity开始说起在应用层开发时，Acitvity跳转会写出下面的代码： 1">
<meta name="keywords" content="android">
<meta property="og:type" content="article">
<meta property="og:title" content="Android中Activity的启动流程">
<meta property="og:url" content="http://zhangsunyucong.top/2018/01/31/android-activity-start-up/index.html">
<meta property="og:site_name" content="长孙雨聪--七星上将">
<meta property="og:description" content="前言在这篇文章中，将会基于android 26源码上分析Activity从启动到显示到屏幕和Decorview添加到Window中的过程。另外在本文中，省略了很多内容，目的只是从源码中找到一条启动的线索。迟点再补充上流程图。 从startActivity开始说起在应用层开发时，Acitvity跳转会写出下面的代码： 123456public static void startAtcivity(B">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android-activity-start-up-1.png?imageView2/2/w/640">
<meta property="og:image" content="http://o8bym0zmt.bkt.clouddn.com/android-activity-start-up-2.png?imageView2/2/w/640">
<meta property="og:updated_time" content="2018-02-01T03:27:31.552Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android中Activity的启动流程">
<meta name="twitter:description" content="前言在这篇文章中，将会基于android 26源码上分析Activity从启动到显示到屏幕和Decorview添加到Window中的过程。另外在本文中，省略了很多内容，目的只是从源码中找到一条启动的线索。迟点再补充上流程图。 从startActivity开始说起在应用层开发时，Acitvity跳转会写出下面的代码： 123456public static void startAtcivity(B">
<meta name="twitter:image" content="http://o8bym0zmt.bkt.clouddn.com/android-activity-start-up-1.png?imageView2/2/w/640">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":false,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://zhangsunyucong.top/2018/01/31/android-activity-start-up/"/>





  <title>Android中Activity的启动流程 | 长孙雨聪--七星上将</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
	
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">长孙雨聪--七星上将</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">坚持不懈，必有回响。</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-music">
          <a href="/music/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-music"></i> <br />
            
            音乐
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-github">
          <a href="https://github.com/zhangsunyucong?tab=repositories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            Github
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
  
     

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://zhangsunyucong.top/2018/01/31/android-activity-start-up/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="长孙雨聪--七星上将">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/myphoto.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="长孙雨聪--七星上将">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Android中Activity的启动流程</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-31T13:08:09+08:00">
                2018-01-31
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2018-02-01T11:27:31+08:00">
                2018-02-01
              </time>
            
          </span>

          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2018/01/31/android-activity-start-up/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2018/01/31/android-activity-start-up/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/2018/01/31/android-activity-start-up/" class="leancloud_visitors" data-flag-title="Android中Activity的启动流程">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,409字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  19分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <script src="\assets\js\APlayer.min.js"> </script><hr>
<h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>在这篇文章中，将会基于android 26源码上分析Activity从启动到显示到屏幕和Decorview添加到Window中的过程。另外在本文中，省略了很多内容，目的只是从源码中找到一条启动的线索。迟点再补充上流程图。</p>
<h3 id="从startActivity开始说起"><a href="#从startActivity开始说起" class="headerlink" title="从startActivity开始说起"></a>从startActivity开始说起</h3><p>在应用层开发时，Acitvity跳转会写出下面的代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">public static void startAtcivity(BaseActivity activity) &#123;</span><br><span class="line">        if(activity != null) &#123;</span><br><span class="line">            Intent intent = new Intent(activity, HomeAcivity.class);</span><br><span class="line">            activity.startActivity(intent);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
 <a id="more"></a>
<p>首先看下activity的继承关系：</p>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android-activity-start-up-1.png?imageView2/2/w/640" alt="context继承关系"></p>
<p><img src="http://o8bym0zmt.bkt.clouddn.com/android-activity-start-up-2.png?imageView2/2/w/640" alt="activity继承关系"></p>
<p>第一张图，知道activity是context的子类，第二张图，我们可以知道各种activity的关系。<br>另外会写一片文章，介绍context。</p>
<p>现在我们进入activity#startActivity<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public void startActivity(Intent intent) &#123;</span><br><span class="line">    this.startActivity(intent, null);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@Override</span><br><span class="line">public void startActivity(Intent intent, @Nullable Bundle options) &#123;</span><br><span class="line">    if (options != null) &#123;</span><br><span class="line">        startActivityForResult(intent, -1, options);</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        // Note we want to go through this call for compatibility with</span><br><span class="line">        // applications that may have overridden the method.</span><br><span class="line">        startActivityForResult(intent, -1);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>接着调用activity#startActivityForResult<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,</span><br><span class="line">        @Nullable Bundle options) &#123;</span><br><span class="line">    </span><br><span class="line">    if (mParent == null) &#123;</span><br><span class="line">        options = transferSpringboardActivityOptions(options);</span><br><span class="line">        //1、Instrumentation</span><br><span class="line">        Instrumentation.ActivityResult ar =</span><br><span class="line">            mInstrumentation.execStartActivity(</span><br><span class="line">                this, mMainThread.getApplicationThread(), mToken, this,</span><br><span class="line">                intent, requestCode, options);</span><br><span class="line">        if (ar != null) &#123;</span><br><span class="line">            mMainThread.sendActivityResult(</span><br><span class="line">                mToken, mEmbeddedID, requestCode, ar.getResultCode(),</span><br><span class="line">                ar.getResultData());</span><br><span class="line">        &#125;</span><br><span class="line">     ...</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在1、中，出现了Instrumentation，并调用了execStartActivity方法<br>进入Instrumentation#execStartActivity<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">public ActivityResult execStartActivity(</span><br><span class="line">        Context who, IBinder contextThread, IBinder token, Activity target,</span><br><span class="line">        Intent intent, int requestCode, Bundle options) &#123;</span><br><span class="line">    IApplicationThread whoThread = (IApplicationThread) contextThread;</span><br><span class="line">   ...</span><br><span class="line">    if (mActivityMonitors != null) &#123;</span><br><span class="line">        synchronized (mSync) &#123;</span><br><span class="line">            final int N = mActivityMonitors.size();</span><br><span class="line">            for (int i=0; i&lt;N; i++) &#123;</span><br><span class="line">                final ActivityMonitor am = mActivityMonitors.get(i);</span><br><span class="line">                ActivityResult result = null;</span><br><span class="line">                if (am.ignoreMatchingSpecificIntents()) &#123;</span><br><span class="line">                    result = am.onStartActivity(intent);</span><br><span class="line">                &#125;</span><br><span class="line">                ...</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    try &#123;</span><br><span class="line">        ...</span><br><span class="line">        //1、进入ActivityManagerService中</span><br><span class="line">        int result = ActivityManager.getService()</span><br><span class="line">            .startActivity(whoThread, who.getBasePackageName(), intent,</span><br><span class="line">                    intent.resolveTypeIfNeeded(who.getContentResolver()),</span><br><span class="line">                    token, target != null ? target.mEmbeddedID : null,</span><br><span class="line">                    requestCode, 0, null, options);</span><br><span class="line">        //2、检查创建actiity过程是否产生了异常            </span><br><span class="line">        checkStartActivityResult(result, intent);</span><br><span class="line">    &#125; catch (RemoteException e) &#123;</span><br><span class="line">        throw new RuntimeException(&quot;Failure from system&quot;, e);</span><br><span class="line">    &#125;</span><br><span class="line">    return null;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在1、中，出现了ActivityManager。取到IActivityManager，这里有涉及binder机制，ActivityManager.getService()得到的就是ActivityManagerService，ActivityManagerService实现了IActivityManager.Stub，而ActivityManager中有IActivityManager.Stub.asInterface的远程调用。<br>ActivityManager#getService<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"> public static IActivityManager getService() &#123;</span><br><span class="line">     return IActivityManagerSingleton.get();</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line">private static final Singleton&lt;IActivityManager&gt; IActivityManagerSingleton =</span><br><span class="line">         new Singleton&lt;IActivityManager&gt;() &#123;</span><br><span class="line">             @Override</span><br><span class="line">             protected IActivityManager create() &#123;</span><br><span class="line">                 final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);</span><br><span class="line">                 final IActivityManager am = IActivityManager.Stub.asInterface(b);</span><br><span class="line">                 return am;</span><br><span class="line">             &#125;</span><br><span class="line">         &#125;;</span><br></pre></td></tr></table></figure></p>
<p>在2、中，Instrumentation#checkStartActivityResult方法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">/** @hide */</span><br><span class="line">public static void checkStartActivityResult(int res, Object intent) &#123;</span><br><span class="line">    if (!ActivityManager.isStartResultFatalError(res)) &#123;</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    switch (res) &#123;</span><br><span class="line">        case ActivityManager.START_INTENT_NOT_RESOLVED:</span><br><span class="line">        case ActivityManager.START_CLASS_NOT_FOUND:</span><br><span class="line">            if (intent instanceof Intent &amp;&amp; ((Intent)intent).getComponent() != null)</span><br><span class="line">            //1、出现没有注册异常</span><br><span class="line">                throw new ActivityNotFoundException(</span><br><span class="line">                        &quot;Unable to find explicit activity class &quot;</span><br><span class="line">                        + ((Intent)intent).getComponent().toShortString()</span><br><span class="line">                        + &quot;; have you declared this activity in your AndroidManifest.xml?&quot;);</span><br><span class="line">            throw new ActivityNotFoundException(</span><br><span class="line">                    &quot;No Activity found to handle &quot; + intent);</span><br><span class="line">        case ActivityManager.START_PERMISSION_DENIED:</span><br><span class="line">            throw new SecurityException(&quot;Not allowed to start activity &quot;</span><br><span class="line">                    + intent);</span><br><span class="line">        case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:</span><br><span class="line">            throw new AndroidRuntimeException(</span><br><span class="line">                    &quot;FORWARD_RESULT_FLAG used while also requesting a result&quot;);</span><br><span class="line">        case ActivityManager.START_NOT_ACTIVITY:</span><br><span class="line">            throw new IllegalArgumentException(</span><br><span class="line">                    &quot;PendingIntent is not an activity&quot;);</span><br><span class="line">        case ActivityManager.START_NOT_VOICE_COMPATIBLE:</span><br><span class="line">            throw new SecurityException(</span><br><span class="line">                    &quot;Starting under voice control not allowed for: &quot; + intent);</span><br><span class="line">        case ActivityManager.START_VOICE_NOT_ACTIVE_SESSION:</span><br><span class="line">            throw new IllegalStateException(</span><br><span class="line">                    &quot;Session calling startVoiceActivity does not match active session&quot;);</span><br><span class="line">        case ActivityManager.START_VOICE_HIDDEN_SESSION:</span><br><span class="line">            throw new IllegalStateException(</span><br><span class="line">                    &quot;Cannot start voice activity on a hidden session&quot;);</span><br><span class="line">        case ActivityManager.START_ASSISTANT_NOT_ACTIVE_SESSION:</span><br><span class="line">            throw new IllegalStateException(</span><br><span class="line">                    &quot;Session calling startAssistantActivity does not match active session&quot;);</span><br><span class="line">        case ActivityManager.START_ASSISTANT_HIDDEN_SESSION:</span><br><span class="line">            throw new IllegalStateException(</span><br><span class="line">                    &quot;Cannot start assistant activity on a hidden session&quot;);</span><br><span class="line">        case ActivityManager.START_CANCELED:</span><br><span class="line">            throw new AndroidRuntimeException(&quot;Activity could not be started for &quot;</span><br><span class="line">                    + intent);</span><br><span class="line">        default:</span><br><span class="line">            throw new AndroidRuntimeException(&quot;Unknown error code &quot;</span><br><span class="line">                    + res + &quot; when starting &quot; + intent);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这是检查在启动activity过程中，可能出现的异常。比如，启动的Acitivity没有在AndroidManifest.xml中注册，会出现代码中1、的异常。</p>
<p>继续，回到在execStartActivity的1、进入ActivityManagerService#startActivity</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public int startActivity(IBinder whoThread, String callingPackage,</span><br><span class="line">        Intent intent, String resolvedType, Bundle bOptions) &#123;</span><br><span class="line">    checkCaller();</span><br><span class="line"></span><br><span class="line">    int callingUser = UserHandle.getCallingUserId();</span><br><span class="line">    TaskRecord tr;</span><br><span class="line">    IApplicationThread appThread;</span><br><span class="line">    synchronized (ActivityManagerService.this) &#123;</span><br><span class="line">        tr = mStackSupervisor.anyTaskForIdLocked(mTaskId);</span><br><span class="line">        if (tr == null) &#123;</span><br><span class="line">            throw new IllegalArgumentException(&quot;Unable to find task ID &quot; + mTaskId);</span><br><span class="line">        &#125;</span><br><span class="line">        //1、IApplicationThread</span><br><span class="line">        appThread = IApplicationThread.Stub.asInterface(whoThread);</span><br><span class="line">        if (appThread == null) &#123;</span><br><span class="line">            throw new IllegalArgumentException(&quot;Bad app thread &quot; + appThread);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    //2、ActivityStarter</span><br><span class="line">    return mActivityStarter.startActivityMayWait(appThread, -1, callingPackage, intent,</span><br><span class="line">            resolvedType, null, null, null, null, 0, 0, null, null,</span><br><span class="line">            null, bOptions, false, callingUser, null, tr, &quot;AppTaskImpl&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在1、处，出现了IApplicationThread，这里涉及到了binder机制，IApplicationThread的实现是在ActivityThread中的内部类ApplicationThread</p>
<p>ActivityThread#ApplicationThread</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br></pre></td><td class="code"><pre><span class="line"> private class ApplicationThread extends IApplicationThread.Stub &#123;</span><br><span class="line">   </span><br><span class="line">...</span><br><span class="line"></span><br><span class="line">     private void updatePendingConfiguration(Configuration config) &#123;</span><br><span class="line">        ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     public final void schedulePauseActivity(IBinder token, boolean finished,</span><br><span class="line">          ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     public final void scheduleStopActivity(IBinder token, boolean showWindow,</span><br><span class="line">             int configChanges) &#123;</span><br><span class="line">         ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     public final void scheduleWindowVisibility(IBinder token, boolean showWindow) &#123;</span><br><span class="line">         ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line"> </span><br><span class="line">     public final void scheduleResumeActivity(IBinder token, int processState,</span><br><span class="line">             boolean isForward, Bundle resumeArgs) &#123;</span><br><span class="line">         ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     public final void scheduleSendResult(IBinder token, List&lt;ResultInfo&gt; results) &#123;</span><br><span class="line">         ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     @Override</span><br><span class="line">     public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,</span><br><span class="line">             ActivityInfo info, Configuration curConfig, Configuration overrideConfig,</span><br><span class="line">             CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,</span><br><span class="line">             int procState, Bundle state, PersistableBundle persistentState,</span><br><span class="line">             List&lt;ResultInfo&gt; pendingResults, List&lt;ReferrerIntent&gt; pendingNewIntents,</span><br><span class="line">             boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) &#123;</span><br><span class="line"></span><br><span class="line">        ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     @Override</span><br><span class="line">     public final void scheduleRelaunchActivity(IBinder token,</span><br><span class="line">             List&lt;ResultInfo&gt; pendingResults, List&lt;ReferrerIntent&gt; pendingNewIntents,</span><br><span class="line">             int configChanges, boolean notResumed, Configuration config,</span><br><span class="line">             Configuration overrideConfig, boolean preserveWindow) &#123;</span><br><span class="line">        ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     public final void scheduleNewIntent(</span><br><span class="line">             List&lt;ReferrerIntent&gt; intents, IBinder token, boolean andPause) &#123;</span><br><span class="line">         ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     public final void scheduleDestroyActivity(IBinder token, boolean finishing,</span><br><span class="line">             int configChanges) &#123;</span><br><span class="line">         ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     public final void scheduleReceiver(Intent intent, ActivityInfo info,</span><br><span class="line">             CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,</span><br><span class="line">             boolean sync, int sendingUser, int processState) &#123;</span><br><span class="line">         ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">     public final void scheduleCreateService(IBinder token,</span><br><span class="line">             ServiceInfo info, CompatibilityInfo compatInfo, int processState) &#123;</span><br><span class="line">        ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     public final void scheduleBindService(IBinder token, Intent intent,</span><br><span class="line">             boolean rebind, int processState) &#123;</span><br><span class="line">         ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     public final void scheduleUnbindService(IBinder token, Intent intent) &#123;</span><br><span class="line">        ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) &#123;</span><br><span class="line">         List&lt;ServiceStartArgs&gt; list = args.getList();</span><br><span class="line"> ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     public final void scheduleStopService(IBinder token) &#123;</span><br><span class="line">         ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     public final void bindApplication(String processName, ApplicationInfo appInfo,</span><br><span class="line">             List&lt;ProviderInfo&gt; providers, ComponentName instrumentationName,</span><br><span class="line">             ProfilerInfo profilerInfo, Bundle instrumentationArgs,</span><br><span class="line">             IInstrumentationWatcher instrumentationWatcher,</span><br><span class="line">             IUiAutomationConnection instrumentationUiConnection, int debugMode,</span><br><span class="line">             boolean enableBinderTracking, boolean trackAllocation,</span><br><span class="line">             boolean isRestrictedBackupMode, boolean persistent, Configuration config,</span><br><span class="line">             CompatibilityInfo compatInfo, Map services, Bundle coreSettings,</span><br><span class="line">             String buildSerial) &#123;</span><br><span class="line">...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">     public void scheduleConfigurationChanged(Configuration config) &#123;</span><br><span class="line">         updatePendingConfiguration(config);</span><br><span class="line">         ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">   ...</span><br><span class="line"></span><br><span class="line">     public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,</span><br><span class="line">             int resultCode, String dataStr, Bundle extras, boolean ordered,</span><br><span class="line">             boolean sticky, int sendingUser, int processState) throws RemoteException &#123;</span><br><span class="line">         ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">     @Override</span><br><span class="line">     public void scheduleActivityConfigurationChanged(</span><br><span class="line">             IBinder token, Configuration overrideConfig) &#123;</span><br><span class="line">        ...</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">   ...</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>在ApplicationThread中，有很多与Activity，service，Application生命周期有关的方法。<br>其中scheduleLaunchActivity()应该就是负责Activity创建的。</p>
<p>ActivityManagerService#startActivity的2、处，调用了ActivityStarter的startActivityMayWait方法，它又调用了startActivityLocked方法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">   1、</span><br><span class="line">   int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,</span><br><span class="line">          ...</span><br><span class="line"></span><br><span class="line">       mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,</span><br><span class="line">               aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,</span><br><span class="line">               callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,</span><br><span class="line">               options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,</span><br><span class="line">               container, inTask);</span><br><span class="line"></span><br><span class="line">      ...</span><br><span class="line">       return mLastStartActivityResult;</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   2、</span><br><span class="line">private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,</span><br><span class="line">           String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,</span><br><span class="line">           IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,</span><br><span class="line">           IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,</span><br><span class="line">           String callingPackage, int realCallingPid, int realCallingUid, int startFlags,</span><br><span class="line">           ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,</span><br><span class="line">           ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,</span><br><span class="line">           TaskRecord inTask) &#123;</span><br><span class="line">     ...</span><br><span class="line"></span><br><span class="line">       return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,</span><br><span class="line">               options, inTask, outActivity);</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   3、</span><br><span class="line">   private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,</span><br><span class="line">      ...</span><br><span class="line">       try &#123;</span><br><span class="line">           mService.mWindowManager.deferSurfaceLayout();</span><br><span class="line">           result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,</span><br><span class="line">                   startFlags, doResume, options, inTask, outActivity);</span><br><span class="line">       &#125; finally &#123;</span><br><span class="line">           ...</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">      ...</span><br><span class="line">       return result;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>在3、中，调用了startActivityUnchecked方法，startActivityUnchecked又调用了ActivityStackSupervisor#resumeFocusedStackTopActivityLocked方法，</p>
<p>ActivityStackSupervisor#resumeFocusedStackTopActivityLocked<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">boolean resumeFocusedStackTopActivityLocked(</span><br><span class="line">        ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) &#123;</span><br><span class="line">    if (targetStack != null &amp;&amp; isFocusedStack(targetStack)) &#123;</span><br><span class="line">        return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);</span><br><span class="line">    &#125;</span><br><span class="line">    final ActivityRecord r = mFocusedStack.topRunningActivityLocked();</span><br><span class="line">    if (r == null || r.state != RESUMED) &#123;</span><br><span class="line">        mFocusedStack.resumeTopActivityUncheckedLocked(null, null);</span><br><span class="line">    &#125; else if (r.state == RESUMED) &#123;</span><br><span class="line">        // Kick off any lingering app transitions form the MoveTaskToFront operation.</span><br><span class="line">        mFocusedStack.executeAppTransition(targetOptions);</span><br><span class="line">    &#125;</span><br><span class="line">    return false;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面方法中，接着调用ActivityStack的resumeTopActivityUncheckedLocked方法，<br>ActivityStack#resumeTopActivityUncheckedLocked<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) &#123;</span><br><span class="line">    if (mStackSupervisor.inResumeTopActivity) &#123;</span><br><span class="line">        // Don&apos;t even start recursing.</span><br><span class="line">        return false;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    boolean result = false;</span><br><span class="line">    try &#123;</span><br><span class="line">        // Protect against recursion.</span><br><span class="line">        mStackSupervisor.inResumeTopActivity = true;</span><br><span class="line">        result = resumeTopActivityInnerLocked(prev, options);</span><br><span class="line">    &#125; finally &#123;</span><br><span class="line">        mStackSupervisor.inResumeTopActivity = false;</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br><span class="line"></span><br><span class="line">    return result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>接着调用resumeTopActivityInnerLocked方法，在resumeTopActivityInnerLocked中调用ActivityStackSupervisor的startSpecificActivityLocked方法</p>
<p>ActivityStackSupervisor#startSpecificActivityLocked<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">void startSpecificActivityLocked(ActivityRecord r,</span><br><span class="line">        boolean andResume, boolean checkConfig) &#123;</span><br><span class="line">    ...</span><br><span class="line">    if (app != null &amp;&amp; app.thread != null) &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            if ((r.info.flags&amp;ActivityInfo.FLAG_MULTIPROCESS) == 0</span><br><span class="line">                    || !&quot;android&quot;.equals(r.info.packageName)) &#123;</span><br><span class="line">               ...</span><br><span class="line">            &#125;</span><br><span class="line">            realStartActivityLocked(r, app, andResume, checkConfig);</span><br><span class="line">            return;</span><br><span class="line">        &#125; catch (RemoteException e) &#123;</span><br><span class="line">           ...</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,</span><br><span class="line">            &quot;activity&quot;, r.intent.getComponent(), false, false, true);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>方法中调用了realStartActivityLocked方法，它里面有下面的代码：</p>
<p>ActivityStackSupervisor#realStartActivityLocked<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,</span><br><span class="line">		System.identityHashCode(r), r.info,</span><br><span class="line">		// TODO: Have this take the merged configuration instead of separate global and</span><br><span class="line">        // override configs.</span><br><span class="line">        mergedConfiguration.getGlobalConfiguration(),</span><br><span class="line">        mergedConfiguration.getOverrideConfiguration(), r.compat,</span><br><span class="line">        r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,</span><br><span class="line">        r.persistentState, results, newIntents, !andResume,</span><br><span class="line">         mService.isNextTransitionForward(), profilerInfo);</span><br></pre></td></tr></table></figure></p>
<p>上面的app.thread就是ApplicationThread,并调用scheduleLaunchActivity。</p>
<p>上面曾经说过ApplicationThread是AcitivityThread的内部类。</p>
<p>进入ApplicationThread的scheduleLaunchActivity方法，它最后会发送一个消息给名为H的handler</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sendMessage(H.LAUNCH_ACTIVITY, r);</span><br></pre></td></tr></table></figure>
<p>H.LAUNCH_ACTIVITY的消息处理逻辑是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">case LAUNCH_ACTIVITY: &#123;</span><br><span class="line">                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, &quot;activityStart&quot;);</span><br><span class="line">                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;</span><br><span class="line"></span><br><span class="line">                    r.packageInfo = getPackageInfoNoCheck(</span><br><span class="line">                            r.activityInfo.applicationInfo, r.compatInfo);</span><br><span class="line">                    handleLaunchActivity(r, null, &quot;LAUNCH_ACTIVITY&quot;);</span><br><span class="line">                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);</span><br><span class="line">                &#125; break;</span><br></pre></td></tr></table></figure>
<p>调用handleLaunchActivity方法。在handleLaunchActivity主要是分别调用performLaunchActivity和handleResumeActivity方法</p>
<p>进入ActivityThread#performLaunchActivity</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line">private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) &#123;</span><br><span class="line">        // System.out.println(&quot;##### [&quot; + System.currentTimeMillis() + &quot;] ActivityThread.performLaunchActivity(&quot; + r + &quot;)&quot;);</span><br><span class="line">        //1、收集创建Acitivity的信息</span><br><span class="line">        ActivityInfo aInfo = r.activityInfo;</span><br><span class="line">        if (r.packageInfo == null) &#123;</span><br><span class="line">            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,</span><br><span class="line">                    Context.CONTEXT_INCLUDE_CODE);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line">        //2、创建Context的实现者ContextImpl</span><br><span class="line">        ContextImpl appContext = createBaseContextForActivity(r);</span><br><span class="line">        Activity activity = null;</span><br><span class="line">        try &#123;</span><br><span class="line">			//3、通Instrumentation创建activity</span><br><span class="line">            java.lang.ClassLoader cl = appContext.getClassLoader();</span><br><span class="line">            activity = mInstrumentation.newActivity(</span><br><span class="line">                    cl, component.getClassName(), r.intent);</span><br><span class="line">            ...</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            ...</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        try &#123;</span><br><span class="line">            //4、创建Application</span><br><span class="line">            Application app = r.packageInfo.makeApplication(false, mInstrumentation);</span><br><span class="line"></span><br><span class="line">           ...</span><br><span class="line">            if (activity != null) &#123;</span><br><span class="line">                ...</span><br><span class="line">                appContext.setOuterContext(activity);</span><br><span class="line">                //5、调用activity的attach方法</span><br><span class="line">                activity.attach(appContext, this, getInstrumentation(), r.token,</span><br><span class="line">                        r.ident, app, r.intent, r.activityInfo, title, r.parent,</span><br><span class="line">                        r.embeddedID, r.lastNonConfigurationInstances, config,</span><br><span class="line">                        r.referrer, r.voiceInteractor, window, r.configCallback);</span><br><span class="line">                ...</span><br><span class="line">                </span><br><span class="line">               if (theme != 0) &#123;</span><br><span class="line">                    activity.setTheme(theme);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                activity.mCalled = false;</span><br><span class="line">                if (r.isPersistable()) &#123;</span><br><span class="line">                    //6、调用Activity的OnCreate方法</span><br><span class="line">                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);</span><br><span class="line">                &#125; else &#123;</span><br><span class="line">                    mInstrumentation.callActivityOnCreate(activity, r.state);</span><br><span class="line">                &#125;            </span><br><span class="line"></span><br><span class="line">                ...</span><br><span class="line">                //7、调用Activity的OnStart方法</span><br><span class="line">                 if (!r.activity.mFinished) &#123;</span><br><span class="line">                    activity.performStart();</span><br><span class="line">                    r.stopped = false;</span><br><span class="line">                &#125;</span><br><span class="line">                </span><br><span class="line">                ...</span><br><span class="line">            &#125;</span><br><span class="line">            r.paused = true;</span><br><span class="line"></span><br><span class="line">            mActivities.put(r.token, r);</span><br><span class="line"></span><br><span class="line">        &#125; catch (SuperNotCalledException e) &#123;</span><br><span class="line">            throw e;</span><br><span class="line"></span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            ...</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        return activity;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>在3、中，会调用Instrumentation#newActivity</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">public Activity newActivity(ClassLoader cl, String className,</span><br><span class="line">            Intent intent)</span><br><span class="line">            throws InstantiationException, IllegalAccessException,</span><br><span class="line">            ClassNotFoundException &#123;</span><br><span class="line">        return (Activity)cl.loadClass(className).newInstance();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>可以看出是通过类加载器通过反射创建Activity实例的。</p>
<p>在4、中，调用了LoadedApk#makeApplication方法，</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">app = mActivityThread.mInstrumentation.newApplication(</span><br><span class="line">                    cl, appClass, appContext);</span><br></pre></td></tr></table></figure>
<p>makeApplication方法中，和newActivity差不多，也是由Instrumentation的newApplication方法，通过反射创建Application的</p>
<p>5、中调用Acitivty的attach方法，</p>
<p>Acitivty#attach<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">final void attach(Context context, ActivityThread aThread,</span><br><span class="line">        Instrumentation instr, IBinder token, int ident,</span><br><span class="line">        Application application, Intent intent, ActivityInfo info,</span><br><span class="line">        CharSequence title, Activity parent, String id,</span><br><span class="line">        NonConfigurationInstances lastNonConfigurationInstances,</span><br><span class="line">        Configuration config, String referrer, IVoiceInteractor voiceInteractor,</span><br><span class="line">        Window window, ActivityConfigCallback activityConfigCallback) &#123;</span><br><span class="line">    attachBaseContext(context);</span><br><span class="line"></span><br><span class="line">    mFragments.attachHost(null /*parent*/);</span><br><span class="line"></span><br><span class="line">    mWindow = new PhoneWindow(this, window, activityConfigCallback);</span><br><span class="line">    mWindow.setWindowControllerCallback(this);</span><br><span class="line">    mWindow.setCallback(this);</span><br><span class="line">    mWindow.setOnWindowDismissedCallback(this);</span><br><span class="line">    mWindow.getLayoutInflater().setPrivateFactory(this);</span><br><span class="line">    ...</span><br><span class="line">    mUiThread = Thread.currentThread();</span><br><span class="line">    ...</span><br><span class="line">    mWindow.setWindowManager(</span><br><span class="line">            (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),</span><br><span class="line">            mToken, mComponent.flattenToString(),</span><br><span class="line">            (info.flags &amp; ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);</span><br><span class="line">    if (mParent != null) &#123;</span><br><span class="line">        mWindow.setContainer(mParent.getWindow());</span><br><span class="line">    &#125;</span><br><span class="line">    mWindowManager = mWindow.getWindowManager();</span><br><span class="line">    mCurrentConfig = config;</span><br><span class="line"></span><br><span class="line">    mWindow.setColorMode(info.colorMode);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在该方法中，主要是会创建PhoneWindow。</p>
<p>在6和7中，分别调用了acitivity的生命周期方法，onCreate和onStart。</p>
<p>已经分析了在handleLaunchActivity的performLaunchActivity方法。<br>现在分析handleLaunchActivity的handleResumeActivity，在handleResumeActivity中会调用acitivity的生命周期方法onResume和将Decorview添加到Window中，并在makeVisible中显示出来。</p>
<p>Activity#handleResumeActivity<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br></pre></td><td class="code"><pre><span class="line">final void handleResumeActivity(IBinder token,</span><br><span class="line">            boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) &#123;</span><br><span class="line">        ActivityClientRecord r = mActivities.get(token);</span><br><span class="line">        if (!checkAndUpdateLifecycleSeq(seq, r, &quot;resumeActivity&quot;)) &#123;</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        // If we are getting ready to gc after going to the background, well</span><br><span class="line">        // we are back active so skip it.</span><br><span class="line">        unscheduleGcIdler();</span><br><span class="line">        mSomeActivitiesChanged = true;</span><br><span class="line"></span><br><span class="line">        //1、会调用Acitvity的onResume生命周期方法</span><br><span class="line">        // TODO Push resumeArgs into the activity for consideration</span><br><span class="line">        r = performResumeActivity(token, clearHide, reason);</span><br><span class="line"></span><br><span class="line">        if (r != null) &#123;</span><br><span class="line">            final Activity a = r.activity;</span><br><span class="line"></span><br><span class="line">            ...</span><br><span class="line">            if (!willBeVisible) &#123;</span><br><span class="line">                try &#123;</span><br><span class="line">                    willBeVisible = ActivityManager.getService().willActivityBeVisible(</span><br><span class="line">                            a.getActivityToken());</span><br><span class="line">                &#125; catch (RemoteException e) &#123;</span><br><span class="line">                    throw e.rethrowFromSystemServer();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            if (r.window == null &amp;&amp; !a.mFinished &amp;&amp; willBeVisible) &#123;</span><br><span class="line">                r.window = r.activity.getWindow();</span><br><span class="line">                View decor = r.window.getDecorView();</span><br><span class="line">                //2、设置decor不可见</span><br><span class="line">                decor.setVisibility(View.INVISIBLE);</span><br><span class="line">                ViewManager wm = a.getWindowManager();</span><br><span class="line">                WindowManager.LayoutParams l = r.window.getAttributes();</span><br><span class="line">                a.mDecor = decor;</span><br><span class="line">                l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;</span><br><span class="line">                l.softInputMode |= forwardBit;</span><br><span class="line">                if (r.mPreserveWindow) &#123;</span><br><span class="line">                    a.mWindowAdded = true;</span><br><span class="line">                    r.mPreserveWindow = false;</span><br><span class="line">                    // Normally the ViewRoot sets up callbacks with the Activity</span><br><span class="line">                    // in addView-&gt;ViewRootImpl#setView. If we are instead reusing</span><br><span class="line">                    // the decor view we have to notify the view root that the</span><br><span class="line">                    // callbacks may have changed.</span><br><span class="line">                    ViewRootImpl impl = decor.getViewRootImpl();</span><br><span class="line">                    if (impl != null) &#123;</span><br><span class="line">                        impl.notifyChildRebuilt();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                if (a.mVisibleFromClient) &#123;</span><br><span class="line">                    if (!a.mWindowAdded) &#123;</span><br><span class="line">                        a.mWindowAdded = true;</span><br><span class="line">                        //3、将Decorviewt添加到Window</span><br><span class="line">                        wm.addView(decor, l);</span><br><span class="line">                    &#125; else &#123;</span><br><span class="line">                        // The activity will get a callback for this &#123;@link LayoutParams&#125; change</span><br><span class="line">                        // earlier. However, at that time the decor will not be set (this is set</span><br><span class="line">                        // in this method), so no action will be taken. This call ensures the</span><br><span class="line">                        // callback occurs with the decor set.</span><br><span class="line">                        a.onWindowAttributesChanged(l);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">            // If the window has already been added, but during resume</span><br><span class="line">            // we started another activity, then don&apos;t yet make the</span><br><span class="line">            // window visible.</span><br><span class="line">            &#125; else if (!willBeVisible) &#123;</span><br><span class="line">                if (localLOGV) Slog.v(</span><br><span class="line">                    TAG, &quot;Launch &quot; + r + &quot; mStartedActivity set&quot;);</span><br><span class="line">                r.hideForNow = true;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            // Get rid of anything left hanging around.</span><br><span class="line">            cleanUpPendingRemoveWindows(r, false /* force */);</span><br><span class="line"></span><br><span class="line">            // The window is now visible if it has been added, we are not</span><br><span class="line">            // simply finishing, and we are not starting another activity.</span><br><span class="line">            if (!r.activity.mFinished &amp;&amp; willBeVisible</span><br><span class="line">                    &amp;&amp; r.activity.mDecor != null &amp;&amp; !r.hideForNow) &#123;</span><br><span class="line">                if (r.newConfig != null) &#123;</span><br><span class="line">                    performConfigurationChangedForActivity(r, r.newConfig);</span><br><span class="line">                    if (DEBUG_CONFIGURATION) Slog.v(TAG, &quot;Resuming activity &quot;</span><br><span class="line">                            + r.activityInfo.name + &quot; with newConfig &quot; + r.activity.mCurrentConfig);</span><br><span class="line">                    r.newConfig = null;</span><br><span class="line">                &#125;</span><br><span class="line">                if (localLOGV) Slog.v(TAG, &quot;Resuming &quot; + r + &quot; with isForward=&quot;</span><br><span class="line">                        + isForward);</span><br><span class="line">                WindowManager.LayoutParams l = r.window.getAttributes();</span><br><span class="line">                if ((l.softInputMode</span><br><span class="line">                        &amp; WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)</span><br><span class="line">                        != forwardBit) &#123;</span><br><span class="line">                    l.softInputMode = (l.softInputMode</span><br><span class="line">                            &amp; (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))</span><br><span class="line">                            | forwardBit;</span><br><span class="line">                    if (r.activity.mVisibleFromClient) &#123;</span><br><span class="line">                        ViewManager wm = a.getWindowManager();</span><br><span class="line">                        View decor = r.window.getDecorView();</span><br><span class="line">                        wm.updateViewLayout(decor, l);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                r.activity.mVisibleFromServer = true;</span><br><span class="line">                mNumVisibleActivities++;</span><br><span class="line">                if (r.activity.mVisibleFromClient) &#123;</span><br><span class="line">                    //4、调用makeVisible</span><br><span class="line">                    r.activity.makeVisible();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            ...</span><br><span class="line"></span><br><span class="line">        &#125; else &#123;</span><br><span class="line">           ...</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>在1、处的performResumeActivity方法中，会调用以下代码：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">r.activity.performResume();</span><br></pre></td></tr></table></figure></p>
<p>即调用activity的onResume生命周期方法。</p>
<p>在2、中，设置了Decorview为不可见<br>在3、中，将Decorview添加到window中，由于2中设置了Decorview为不可见，这时view还看不到。<br>在4、中，调用Activity的makeVisible方法。<br>Activity#makeVisible<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">void makeVisible() &#123;</span><br><span class="line">    if (!mWindowAdded) &#123;</span><br><span class="line">        ViewManager wm = getWindowManager();</span><br><span class="line">        wm.addView(mDecor, getWindow().getAttributes());</span><br><span class="line">        mWindowAdded = true;</span><br><span class="line">    &#125;</span><br><span class="line">    mDecor.setVisibility(View.VISIBLE);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面代码中，将Decorview设置为可见的。</p>
<h3 id="剩下问题"><a href="#剩下问题" class="headerlink" title="剩下问题"></a>剩下问题</h3><p>在上面过程中的哪里开始涉及视图绘制。迟点再看。<br>分析追溯到Zygote中。<br>本篇文章的排版还有点乱。</p>
<p>优秀文章：<a href="http://blog.csdn.net/dd864140130/article/details/60466394" target="_blank" rel="noopener">http://blog.csdn.net/dd864140130/article/details/60466394</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
	  
		<!--MOB SHARE BEGIN-->
 <button id="rewardButton" class="-mob-share-open" style="margin-right:5px;">
    <span>分享</span>
  </button>
<div class="-mob-share-ui" style="display: none">
    <ul class="-mob-share-list">
        <li class="-mob-share-weibo"><p>新浪微博</p></li>
            <li class="-mob-share-tencentweibo"><p>腾讯微博</p></li>
            <li class="-mob-share-qzone"><p>QQ空间</p></li>
            <li class="-mob-share-qq"><p>QQ好友</p></li>
            <li class="-mob-share-weixin"><p>微信</p></li>
            <li class="-mob-share-douban"><p>豆瓣</p></li>
            <li class="-mob-share-renren"><p>人人网</p></li>
            <li class="-mob-share-kaixin"><p>开心网</p></li>
            <li class="-mob-share-facebook"><p>Facebook</p></li>
            <li class="-mob-share-twitter"><p>Twitter</p></li>
            <li class="-mob-share-pocket"><p>Pocket</p></li>
            <li class="-mob-share-google"><p>Google+</p></li>
            <li class="-mob-share-youdao"><p>有道云笔记</p></li>
    </ul>
    <div class="-mob-share-close">取消</div>
</div>
<div class="-mob-share-ui-bg"></div>
<script id="-mob-share" src="https://f1.webshare.mob.com/code/mob-share.js?appkey=230df6a994c78"></script>
<!--MOB SHARE END-->
      
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  
  
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="长孙雨聪--七星上将 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="长孙雨聪--七星上将 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    
	
	<div>
	  
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
	  
	</div>

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    长孙雨聪--七星上将
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://zhangsunyucong.top/2018/01/31/android-activity-start-up/" title="Android中Activity的启动流程">http://zhangsunyucong.top/2018/01/31/android-activity-start-up/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/android/" rel="tag"><i class="fa fa-tag"></i> android</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/01/25/android-view-positon-and-scroll/" rel="next" title="Android中view的位置坐标和view的滑动">
                <i class="fa fa-chevron-left"></i> Android中view的位置坐标和view的滑动
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/02/01/android-handler/" rel="prev" title="Android中的消息机制">
                Android中的消息机制 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>

  
	  
	  
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
			<a href="/" class="site-author-image" rel="start" style="border:none">
              <img class="site-author-image" itemprop="image"
                src="/images/myphoto.jpg"
                alt="长孙雨聪--七星上将" />
			</a>	
            
              <p class="site-author-name" itemprop="name">长孙雨聪--七星上将</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/zhangsunyucong?tab=repositories" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:969887864@qq.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            
          </div>

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.wanandroid.com/" title="鸿洋_" target="_blank">鸿洋_</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://luodw.cc/" title="罗道文" target="_blank">罗道文</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://litten.me/" title="Litten" target="_blank">Litten</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://luuman.github.io" title="luuman" target="_blank">luuman</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.barretlee.com" title="小胡子哥" target="_blank">小胡子哥</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.halyul.cc" title="halyul" target="_blank">halyul</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.csdn.net/mine_song/article/details/64121769" title="剑指" target="_blank">剑指</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.ithmz.com/" title="奶爸大哥" target="_blank">奶爸大哥</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ruanyifeng.com" title="阮一峰" target="_blank">阮一峰</a>
                  </li>
                
              </ul>
			   
			   <div id="days"></div>
</script>
<script language="javascript">
function show_date_time(){
	window.setTimeout("show_date_time()", 1000);
	BirthDay = new Date("11/24/2017 15:00:00");
	today  =new Date();
	timeold = (today.getTime()-BirthDay.getTime());
	sectimeold = timeold/1000
	secondsold = Math.floor(sectimeold);
	msPerDay = 24*60*60*1000
	e_daysold = timeold/msPerDay
	daysold = Math.floor(e_daysold);
	e_hrsold = (e_daysold-daysold)*24;
	hrsold = setzero(Math.floor(e_hrsold));
	e_minsold = (e_hrsold-hrsold)*60;
	minsold = setzero(Math.floor((e_hrsold-hrsold)*60));
	seconds = setzero(Math.floor((e_minsold-minsold)*60));
	document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
	if (i<10)
	{
		i="0" + i
	};
	return i;
}
show_date_time();
</script>

			  
            </div>
          

         
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#从startActivity开始说起"><span class="nav-number">2.</span> <span class="nav-text">从startActivity开始说起</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#剩下问题"><span class="nav-number">3.</span> <span class="nav-text">剩下问题</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">长孙雨聪--七星上将</span>
  
</div>

Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  






  
  







  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/canvas_lines.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytlJYAPJ';
      var conf = '72c4d5b62ad9725c5f533c23a6f1097e';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  









  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("2YPqqc43cMkbPegNE3Auieo4-gzGzoHsz", "TVVsPYw3swS3SrByLqNtqlAL");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.3"></script>


  
</body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>
